package com.channel.temperature.collect.ui.activity

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.dao.OfflineBase
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.DisplayUtil
import com.channel.temperature.collect.databinding.ActivityCachedDeviceListBinding
import com.channel.temperature.collect.ui.adapter.CachedDeviceAdapter
import com.channel.temperature.collect.ui.viewmodel.CachedDeviceListModel
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.divider
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.ext.grid
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import me.hgj.mvvmhelper.util.decoration.DividerOrientation
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.utils.ScreenUtils

class CachedDeviceListActivity :
    BaseActivity<CachedDeviceListModel, ActivityCachedDeviceListBinding>() {

    private val deviceAdapter: CachedDeviceAdapter by lazy { CachedDeviceAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        mToolbar.initBack("本地离线数据") {
            finish()
        }
        //初始化 recycleView
        mBind.listRecyclerView.grid(1).divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setDivider(1, true)
            setColor(getColorExt(R.color.common_text_hint_color))
        }.adapter = deviceAdapter

        deviceAdapter.setOnItemClickListener { adapter, view, position ->
            var bundle = Bundle()
            bundle.putString("deviceName", mViewModel.deviceList.get(position))
            mmkv.putBoolean("isLand",DisplayUtil.getScreenHeight(this) < DisplayUtil.getScreenWidth(this))
            bundle.putBoolean(
                "isLand",
                DisplayUtil.getScreenHeight(this) < DisplayUtil.getScreenWidth(this)
            )
            toStartActivity(OfflineDataActivity::class.java, bundle)
        }
        deviceAdapter.setOnItemLongClickListener { adapter, view, position ->
            val messageDialog = MessageDialog.show(
                "提示", "确定删除当前本地数据？", "确定", "取消"
            )
            messageDialog.maxWidth =
                if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                    appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                dialog.dismiss()
                OfflineBase.get(appContext).offlineDao()
                    .deleteRoomFromDeviceName(mViewModel.deviceList.get(position))
                mmkv.remove(mViewModel.deviceList.get(position))
                ToastUtils.show("删除成功")
                mViewModel.deviceList.removeAt(position)
                var tempData = mViewModel.listData.value
                tempData?.removeAt(position)
                mViewModel.listData.value = tempData
                true
            }
            true
        }
        mViewModel.getCachedDataList()
    }

    /**
     * 请求成功
     */
    override fun onRequestSuccess() {
        mViewModel.listData.observe(this, Observer {
            if (it.size == 0) {
                ToastUtils.show("暂无数据")
                mBind.noDataIv.visibility = View.VISIBLE
                deviceAdapter.setNewInstance(it)
                deviceAdapter.notifyDataSetChanged()
            } else {
                mBind.noDataIv.visibility = View.GONE
                deviceAdapter.setNewInstance(it)
                deviceAdapter.notifyDataSetChanged()
            }
        })
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mBind.clearAll,
        ) {
            when (it) {
                mBind.clearAll -> {
                    lifecycleScope.launch {
                        val messageDialog = MessageDialog.show(
                            "提示", "确定清除本地所有离线数据吗？", "确定", "取消"
                        )
                        messageDialog.maxWidth =
                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                                appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                dialog.dismiss()
                                OfflineBase.get(appContext).offlineDao().deleteAll()
                                ToastUtils.show("清除成功")
                                mViewModel.deviceList.clear()
                                var tempData = mViewModel.listData.value
                                tempData?.clear()
                                mViewModel.listData.value = tempData
                                true
                            }

                    }

                }

            }
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        AutoSizeConfig.getInstance().setScreenWidth(ScreenUtils.getScreenSize(this)[0]);
        AutoSizeConfig.getInstance().setScreenHeight(ScreenUtils.getScreenSize(this)[1]);

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            AutoSize.autoConvertDensityBaseOnHeight(this, 640f);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            AutoSize.autoConvertDensityOfGlobal(this);
        }
    }

}